<!-- 商家信息管理 -->
<template>
  <PageContainer title="商家信息管理">
    <div class="merchant-info-container">
      <el-card shadow="hover" style="margin-bottom: 20px;">
        <div class="info-header">
          <h3>基本信息</h3>
          <el-button type="primary" @click="handleEdit">
            <i class="el-icon-edit"></i> 编辑信息
          </el-button>
        </div>
        <el-form :model="merchantInfo" label-width="120px" class="info-form">
          <el-row :gutter="30">
            <el-col :span="12">
              <el-form-item label="商家名称">
                <span class="info-value">{{ merchantInfo.merchantName || '-' }}</span>
              </el-form-item>
              <el-form-item label="联系人">
                <span class="info-value">{{ merchantInfo.contactPerson || '-' }}</span>
              </el-form-item>
              <el-form-item label="联系电话">
                <span class="info-value">{{ merchantInfo.phone || '-' }}</span>
              </el-form-item>
              <el-form-item label="邮箱">
                <span class="info-value">{{ merchantInfo.email || '-' }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="所属地区">
                <span class="info-value">{{ merchantInfo.region || '-' }}</span>
              </el-form-item>
              <el-form-item label="详细地址">
                <span class="info-value">{{ merchantInfo.address || '-' }}</span>
              </el-form-item>
              <el-form-item label="审核状态">
                <el-tag :type="getStatusTagType(merchantInfo.auditStatus)">
                  {{ getStatusLabel(merchantInfo.auditStatus) || '-' }}
                </el-tag>
              </el-form-item>
              <el-form-item label="账号状态">
                <el-tag :type="merchantInfo.status === 1 ? 'success' : 'danger'">
                  {{ merchantInfo.status === 1 ? '正常' : '禁用' }}
                </el-tag>
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item label="商家简介">
            <el-input v-model="merchantInfo.description" type="textarea" :rows="5" disabled
              class="intro-input"></el-input>
          </el-form-item>
          <el-form-item label="营业执照">
            <el-image :src="merchantInfo.businessLicense" style="width: 200px; height: auto; cursor: pointer;"
              fit="contain" @click="handlePreviewLicense"></el-image>
          </el-form-item>
        </el-form>
      </el-card>

      <el-card shadow="hover">
        <div class="info-header">
          <h3>账号安全</h3>
        </div>
        <el-form :model="securityForm" :rules="securityRules" ref="securityFormRef" label-width="120px"
          class="security-form">
          <el-form-item label="原密码" prop="oldPassword">
            <el-input v-model="securityForm.oldPassword" type="password" placeholder="请输入原密码"></el-input>
          </el-form-item>
          <el-form-item label="新密码" prop="newPassword">
            <el-input v-model="securityForm.newPassword" type="password" placeholder="请输入新密码"></el-input>
          </el-form-item>
          <el-form-item label="确认新密码" prop="confirmPassword">
            <el-input v-model="securityForm.confirmPassword" type="password" placeholder="请再次输入新密码"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleChangePassword">修改密码</el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>

    <!-- 编辑信息弹窗 -->
    <el-dialog title="编辑商家信息" :visible.sync="editDialogVisible" width="600px" :before-close="handleDialogClose">
      <el-form :model="editForm" :rules="editRules" ref="editFormRef" label-width="100px">
        <el-form-item label="商家名称" prop="merchantName">
          <el-input v-model="editForm.merchantName" placeholder="请输入商家名称"></el-input>
        </el-form-item>
        <el-form-item label="联系人" prop="contactPerson">
          <el-input v-model="editForm.contactPerson" placeholder="请输入联系人姓名"></el-input>
        </el-form-item>
        <el-form-item label="联系电话" prop="phone">
          <el-input v-model="editForm.phone" placeholder="请输入联系电话"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email" type="email" placeholder="请输入邮箱"></el-input>
        </el-form-item>
        <el-form-item label="所属地区" prop="region">
          <el-select v-model="editForm.region" placeholder="请选择所属地区">
            <el-option label="北京" value="北京"></el-option>
            <el-option label="上海" value="上海"></el-option>
            <el-option label="广州" value="广州"></el-option>
            <el-option label="深圳" value="深圳"></el-option>
            <el-option label="其他" value="其他"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="详细地址" prop="address">
          <el-input v-model="editForm.address" placeholder="请输入详细地址"></el-input>
        </el-form-item>
        <el-form-item label="商家简介" prop="description">
          <el-input v-model="editForm.description" type="textarea" :rows="5" placeholder="请输入商家简介"></el-input>
        </el-form-item>
        <el-form-item label="营业执照" prop="businessLicense">
          <el-upload class="upload-demo" :action="uploadUrl" :on-success="handleLicenseUpload"
            :before-upload="handleBeforeUpload" :file-list="licenseFileList" list-type="picture-card">
            <i class="el-icon-plus"></i>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleEditSubmit">确定</el-button>
      </template>
    </el-dialog>

    <!-- 营业执照预览弹窗 -->
    <el-dialog title="营业执照预览" :visible.sync="licensePreviewVisible" width="600px">
      <el-image :src="merchantInfo.businessLicense" style="width: 100%;" fit="contain"></el-image>
    </el-dialog>
  </PageContainer>
</template>

<script setup>
import { ref, reactive, onMounted, toRefs } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import PageContainer from '@/components/common/PageContainer.vue'
import { getMerchantInfo, updateMerchantInfo, changeMerchantPassword } from '@/api/merchant'

// 商家信息
const merchantInfo = ref({
  id: '',
  merchantName: '',
  contactPerson: '',
  phone: '',
  email: '',
  region: '',
  address: '',
  businessLicense: '',
  description: '',
  auditStatus: '',
  status: 1
})

// 账号安全表单
const securityForm = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

// 安全表单校验规则
const securityRules = reactive({
  oldPassword: [
    { required: true, message: '请输入原密码', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度在6-20位之间', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请再次输入新密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== securityForm.newPassword) {
          callback(new Error('两次输入密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
})

// 弹窗相关
const editDialogVisible = ref(false)
const licensePreviewVisible = ref(false)
const editFormRef = ref(null)
const securityFormRef = ref(null)
const licenseFileList = ref([])
const uploadUrl = import.meta.env.VITE_UPLOAD_URL || '/api/upload'

// 编辑表单
const editForm = reactive({
  id: '',
  merchantName: '',
  contactPerson: '',
  phone: '',
  email: '',
  region: '',
  address: '',
  businessLicense: '',
  description: ''
})

// 编辑表单校验规则
const editRules = reactive({
  merchantName: [
    { required: true, message: '请输入商家名称', trigger: 'blur' }
  ],
  contactPerson: [
    { required: true, message: '请输入联系人姓名', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  region: [
    { required: true, message: '请选择所属地区', trigger: 'change' }
  ],
  address: [
    { required: true, message: '请输入详细地址', trigger: 'blur' }
  ],
  description: [
    { required: true, message: '请输入商家简介', trigger: 'blur' }
  ]
})

// 审核状态标签类型
const getStatusTagType = (status) => {
  const statusTypeMap = {
    pending: 'warning',
    pass: 'success',
    reject: 'danger'
  }
  return statusTypeMap[status] || 'default'
}

// 审核状态文本
const getStatusLabel = (status) => {
  const statusLabelMap = {
    pending: '待审核',
    pass: '已通过',
    reject: '已驳回'
  }
  return statusLabelMap[status] || '未知状态'
}

// 获取商家信息
const fetchMerchantInfo = async () => {
  try {
    const merchantId = localStorage.getItem('merchantId') // 从本地存储获取当前商家ID
    const res = await getMerchantInfo(merchantId)
    merchantInfo.value = res.data
    // 初始化编辑表单
    editForm.id = res.data.id
    editForm.merchantName = res.data.merchantName
    editForm.contactPerson = res.data.contactPerson
    editForm.phone = res.data.phone
    editForm.email = res.data.email
    editForm.region = res.data.region
    editForm.address = res.data.address
    editForm.businessLicense = res.data.businessLicense
    editForm.description = res.data.description
    // 营业执照文件列表
    licenseFileList.value = res.data.businessLicense ? [{ url: res.data.businessLicense }] : []
  } catch (error) {
    ElMessage.error('获取商家信息失败')
  }
}

// 编辑信息
const handleEdit = () => {
  editDialogVisible.value = true
}

// 预览营业执照
const handlePreviewLicense = () => {
  if (merchantInfo.value.businessLicense) {
    licensePreviewVisible.value = true
  } else {
    ElMessage.warning('暂无营业执照图片')
  }
}

// 编辑提交
const handleEditSubmit = async () => {
  try {
    await editFormRef.value.validate()
    await updateMerchantInfo(editForm)
    ElMessage.success('信息修改成功')
    editDialogVisible.value = false
    fetchMerchantInfo() // 重新获取商家信息
  } catch (error) {
    ElMessage.error('信息修改失败')
  }
}

// 修改密码
const handleChangePassword = async () => {
  try {
    await securityFormRef.value.validate()
    const merchantId = localStorage.getItem('merchantId')
    await changeMerchantPassword({
      id: merchantId,
      oldPassword: securityForm.oldPassword,
      newPassword: securityForm.newPassword
    })
    ElMessage.success('密码修改成功，请重新登录')
    // 重置表单
    securityForm.oldPassword = ''
    securityForm.newPassword = ''
    securityForm.confirmPassword = ''
    // 实际项目中可触发退出登录
    // useAuthStore().logout()
    // router.push('/login')
  } catch (error) {
    ElMessage.error(error.message || '密码修改失败')
  }
}

// 营业执照上传成功
const handleLicenseUpload = (response) => {
  editForm.businessLicense = response.data.url
  licenseFileList.value = [{ url: response.data.url }]
}

// 上传前校验
const handleBeforeUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  if (!isImage) {
    ElMessage.error('请上传图片文件')
    return false
  }
  const isLt5M = file.size / 1024 / 1024 < 5
  if (!isLt5M) {
    ElMessage.error('图片大小不能超过5MB')
    return false
  }
  return true
}

// 关闭弹窗
const handleDialogClose = () => {
  editFormRef.value?.resetFields()
  editDialogVisible.value = false
}

// 页面挂载时获取数据
onMounted(() => {
  fetchMerchantInfo()
})
</script>

<style scoped lang="scss">
.merchant-info-container {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.info-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #e6e6e6;

  h3 {
    font-size: 16px;
    font-weight: 600;
    color: #333;
  }
}

.info-form {
  .info-value {
    font-size: 14px;
    color: #666;
  }

  .intro-input {
    background-color: #f5f5f5;
    border-color: #e6e6e6;
  }
}

.security-form {
  margin-top: 10px;
}

:deep(.el-upload--picture-card) {
  width: 120px;
  height: 120px;
}

:deep(.el-upload-list--picture-card .el-upload-list__item) {
  width: 120px;
  height: 120px;
}
</style>